<template>
  <div class="app">
    <p>用户的 ID: {{ userId }}</p>
    <p>音乐类型 ID: {{ musicTypeId }}</p>

    <!--下单-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="purchaseMusic"
        >购买音乐
        </el-button>
      </el-col>
    </el-row>

    <!-- 数据展示区 -->
    <el-table :data="musicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="音乐名称" align="center" prop="musicName" width="150">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.musicName" placement="top">
            <div @click="goToMusicDetail(scope.row)">{{ scope.row.musicName }}</div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="歌手" align="center" prop="singerStr" width="120">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.singerStr" placement="top">
            <div>{{ scope.row.singerStr }}</div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="单价" align="center" prop="musicPrice" width="100">
        <template slot-scope="scope">
          {{ scope.row.musicPrice }}
        </template>
      </el-table-column>

      <el-table-column label="音乐时长" align="center" prop="musicTime" width="100">
        <template slot-scope="scope">
          {{ scope.row.musicTime }} s
        </template>
      </el-table-column>
      <el-table-column label="收藏数" align="center" prop="musicCollect" width="100"/>

      <el-table-column label="图片" align="center" prop="musicImage" width="60">
        <template slot-scope="scope">
          <img :src="scope.row.musicImage" alt="Music Image" style="width: 50px; height: 50px; object-fit: cover;">
        </template>
      </el-table-column>

      <el-table-column label="发布时间" align="center" prop="musicCreateTime" width="180">
        <template slot-scope="scope">
          {{ scope.row.musicCreateTime }}
        </template>
      </el-table-column>

      <audio ref="audioPlayer" style="display: none;"></audio>
      <el-table-column label="播放按钮" align="left" prop="musicAudio" style="width:300px">
        <template slot-scope="scope">
          <div class="audio-player">
            <button
                class="play-button"
                :class="{ playing: currentAudioUrl === scope.row.musicAudio && isPlaying }"
                @click="togglePlay(scope.row.musicAudio, scope.$index)"
            >
              <span
                  :class="currentAudioUrl === scope.row.musicAudio && isPlaying ? 'el-icon-pause' : 'el-icon-video-play'"
                  class="play-icon"></span>
            </button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="queryParams.pageNum"
          :page-size.sync="queryParams.pageSize"
          :page-sizes="[1, 2, 3, 5]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>

    <el-dialog :title=title :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="充值用户">
          <el-input v-model="form.activateUserAccount"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="getOrderSn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import {parseTime} from "@/utils/ruoyi";
import {getUserInfo} from "@/utils/auth";

export default {
  name: 'MainMusic',

  data() {
    return {
      userId: 0,
      currentAudioUrl: '', // 当前播放的音频URL
      isPlaying: false, // 播放状态
      // 总条数
      total: 0,
      musicTypeId: 0,
      // 音乐类型列表表格数据
      musicList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 3,
        musicName: null,
        musicType: null,
        musicPrice: null,
        musicWords: null,
        musicDesc: null,
        musicTime: null,
        musicCollect: null,
        musicSales: null,
        musicImage: null,
        musicStatus: null,
        musicAudio: null,
        musicCreateTime: null
      },
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      toggle: '',
      userInfo: {},
      title:'',
      dialogFormVisible:false,
      form:{
        activateUserAccount:''
      }
    };
  },
  methods: {
    goToMusicDetail(row) {
      const musicId = row.musicId;
      console.log("音乐类型名id:", musicId);
      this.$router.push('/MainIndex?musicId=' + musicId);
      localStorage.setItem("musicId", musicId);
    },
    togglePlay(audioUrl, index) {
      console.log(index)
      if (this.currentAudioUrl === audioUrl) {
        if (this.isPlaying) {
          this.pauseAudio(); // 如果正在播放，则暂停
        } else {
          this.playAudio(audioUrl); // 如果已暂停，则从当前位置继续播放
        }
      } else {
        this.playAudio(audioUrl); // 如果是新的音乐，则播放新音乐
      }
    },
    playAudio(audioUrl) {
      if (this.$refs.audioPlayer) {
        this.currentAudioUrl = audioUrl;
        this.$refs.audioPlayer.src = audioUrl;
        this.$refs.audioPlayer.play()
            .then(() => {
              this.isPlaying = true; // 播放成功，更新播放状态
            })
            .catch(error => {
              console.error("播放音频时出错:", error);
            });
      }
    },
    pauseAudio() {
      if (this.$refs.audioPlayer) {
        this.$refs.audioPlayer.pause();
        this.isPlaying = false; // 暂停，更新播放状态
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    parseTime,
    // 切换播放歌曲
    setMusicUrl(url, id) {
      if (this.url !== url) {
        this.$store.commit('setUrl', url === null ? '' : url)
        this.$store.commit('setIsPlay', true)
        this.toggle = id
        return
      }
      if (this.isPlay) {
        this.toggle = ''
        this.$store.commit('setIsPlay', false)
      } else {
        this.toggle = id
        this.$store.commit('setIsPlay', true)
      }
    },
    // 表单重置
    reset() {
      this.form = {
        musicId: null,
        musicName: null,
        musicType: null,
        musicPrice: null,
        musicWords: null,
        musicDesc: null,
        musicTime: null,
        musicCollect: null,
        musicSales: null,
        musicImage: null,
        musicStatus: null,
        musicAudio: null,
        musicCreateTime: null,
        singerIds: [],

        totalPay: 0,
        orderId: 0
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.musicId);
      console.log("选中的音乐ID:", this.ids);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;

      this.totalPay = 0
      selection.map(item => {
            this.totalPay = this.totalPay + item.musicPrice
          }
      )
    },

    // 通过musicTypeId查询音乐
    /** 查询音乐列表列表 */
    getList() {
      request({
        url: "/music/music/web/list",
        method: "get",
        params: {
          ...this.queryParams,
          musicType: this.musicTypeId
        }
      }).then(response => {
        this.musicList = response.rows;
        this.total = response.total;
        console.log("查询到的音乐列表：", this.musicList);
      })
    },
    purchaseMusic() {
      //打开模态框输入用户
      this.title = '充值用户'
      this.form.activateUserAccount=JSON.parse(localStorage.getItem("userAccount"));
      this.dialogFormVisible=true;

    },
    getOrderSn() {
      if(this.form.activateUserAccount==''||this.form.activateUserAccount==null){
        this.$message({
          type: 'info',
          message: '充值账户不可为空'
        });
        return
      }
      if(this.ids==''||this.ids==null){
        this.$message({
          type: 'info',
          message: '请至少选一个要购买的音乐'
        });
        return
      }

      //生成orderId
      request({
        url: 'order/order/web/getOrderSn',
        method: 'get',
      }).then(response => {
        if (response.code == 200) {
          this.orderId = response.msg;
          //插入订单表,订单音乐表,音乐销量
          this.saleMusic();
        }
      })
    },
    saleMusic() {
      request({
        url: 'order/order/web/saleMusic',
        method: 'post',
        data:{
          orderId:this.orderId,
          activateUserAccount:this.form.activateUserAccount,
          orderTotal:this.totalPay,
          musicIds:this.ids
        }
      }).then(response => {
        if (response.code == 200) {
          this.$router.push('/pay?orderId=' + this.orderId+'&totalPay='+this.totalPay);
        }else{

        }
      })
    }
  },
  created() {
    this.musicTypeId = localStorage.getItem("musicTypeId");
    console.log("从 localStorage 获取的音乐类型 ID:", this.musicTypeId);
    this.getList();
    this.userInfo = getUserInfo()
    this.userId = this.userInfo.userId
    console.log("当前登录的用户 ID:", this.userId);
  }
};
</script>

<style scoped>
.app {
  position: relative;
  top: 60px;
  margin-left: 300px;
  margin-right: 200px;
}

.play-button {
  width: 40px; /* 按钮宽度 */
  height: 40px; /* 按钮高度 */
  border-radius: 50%; /* 圆形按钮 */
  background-color: #409EFF; /* 主题色 */
  color: white; /* 文字颜色 */
  display: flex; /* 弹性布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  cursor: pointer; /* 鼠标手型 */
  border: none; /* 无边框 */
  outline: none; /* 无轮廓线 */
  transition: background-color 0.3s; /* 添加过渡效果 */
}

.play-button:hover {
  background-color: #66b1ff; /* 鼠标悬浮时的颜色 */
}

.play-button.playing {
  //background-color: rgba(214, 99, 232, 0.7); /* 播放时的颜色，透明度为0.7 */
  background: url("../../img/bof.webp") no-repeat;
  background-size: 100%; /* 图片���� */
}

.play-icon {
  font-size: 20px; /* 图标大小 */
}
</style>